import React, { useState, useEffect } from "react";
import {
  Button,
  Form,
  Input,
  Select,
  Switch,
  Table,
  Space,
  Modal,
  message,
  TreeSelect,
} from "antd";
import {
  SearchOutlined,
  ReloadOutlined,
  PlusOutlined,
  DeleteOutlined,
  EditOutlined,
  ExclamationCircleFilled,
} from "@ant-design/icons";
import type { ColumnsType } from "antd/es/table";
import { $get, $post } from "@/api/RestUtils";
import TimeUtils from "@/utils/TimeUtils";
import TreeUtils from "@/utils/TreeUtils";
import "./index.less";
import { useSelector } from "react-redux";

const App: React.FC = () => {
  const permissionList: string[] = useSelector((state: any) => state.permissions);

  const [searchForm] = Form.useForm();
  const [dataForm] = Form.useForm();

  const [infoModalShow, setInfoModalShow] = useState(false);
  const [infoModalTitle, setInfoModalTitle] = useState("");

  const [userList, setUserList] = useState([]);
  const [total, setTotal] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);

  const [roleList, setRoleList] = useState<any[]>([]);
  const [departmentList, setDepartmentList] = useState<any[]>([]);

  const availableList = [
    {
      available: 0,
      availableName: "锁定",
    },
    {
      available: 1,
      availableName: "正常",
    },
  ];
  
  let field = {
    id: "deptId",
    parentId: "parentId"
  }

  const columns: ColumnsType<UserDataType> = [
    {
      title: "用户账号",
      dataIndex: "username",
      key: "username",
      width: 150,
      align: "center",
    },
    {
      title: "用户名称",
      dataIndex: "nickName",
      key: "nickName",
      width: 150,
      align: "center",
    },
    {
      title: "邮箱",
      dataIndex: "mail",
      key: "mail",
      width: 240,
      align: "center",
      render: (mail: string) => {
        return mail ? mail : "-";
      },
    },
    {
      title: "手机号码",
      dataIndex: "phone",
      key: "phone",
      width: 200,
      align: "center",
    },
    {
      title: "状态",
      key: "action",
      width: 100,
      align: "center",
      render: (record: any) => {
        return (
          <Switch
            checked={record.available === 1}
            onClick={(checked, event) =>
              changeAvailable(checked, record.userId)
            }
            disabled={
              !permissionList ||
              !permissionList.includes("system.user:available")
            }
          />
        );
      },
    },
    {
      title: "创建时间",
      dataIndex: "ctime",
      key: "ctime",
      width: 240,
      align: "center",
      render: (ctime: Date) => {
        return TimeUtils.format(ctime);
      },
    },
    {
      title: "操作",
      key: "action",
      fixed: "right",
      align: "center",
      width: 400,
      render: (record: any) => {
        return (
          <Space size="middle">
            <Button
              type="link"
              icon={<EditOutlined />}
              size="small"
              onClick={() => switchDataModalShow(true, 1, record)}
              disabled={
                !permissionList ||
                !permissionList.includes("system.user:update")
              }
            >
              修改
            </Button>
            <Button
              type="link"
              icon={<ReloadOutlined />}
              size="small"
              onClick={() => resetPassConfirm(record.userId)}
              disabled={
                !permissionList ||
                !permissionList.includes("system.user:resetPass")
              }
            >
              重置密码
            </Button>
            <Button
              type="link"
              icon={<DeleteOutlined />}
              size="small"
              onClick={() => deleteUserConfirm(record.userId)}
              disabled={
                !permissionList ||
                !permissionList.includes("system.user:delete")
              }
            >
              删除
            </Button>
          </Space>
        );
      },
    },
  ];

  useEffect(() => {
    getRoleList();
    getDepartmentList();
    search(currentPage, 10);
  }, []);

  const switchDataModalShow = (show: boolean, model: number, formData: any) => {
    setInfoModalShow(show);
    if (model === 0) {
      // 新增
      setInfoModalTitle("新增用户信息");
    } else {
      // 修改
      setInfoModalTitle("修改用户信息");
      dataForm.setFieldsValue(formData);
    }
  };

  const closeModal = () => {
    setInfoModalShow(false);
    resetDataForm();
  };

  const saveOrUpdate = (formData: any) => {
    let url;
    if (formData.userId != null) {
      url = "/user/update";
    } else {
      url = "/user/save";
    }
    $post(url, formData)
      .then((res: any) => {
        if (res.code === 0) {
          message.success(res.msg);
          setCurrentPage(1);
          search(1, 10);
          closeModal();
        } else {
          message.error(res.msg);
        }
      })
      .catch((err: any) => {
        message.error("系统异常");
      });
  };

  const changeAvailable = (checked: boolean, userId: number) => {
    let available = checked ? 1 : 0;
    let param = {
      userId: userId,
      available: available,
    };
    $post("/user/update", param)
      .then((res: any) => {
        if (res.code === 0) {
          message.success(res.msg);
          setCurrentPage(1);
          search(1, 10);
        } else {
          message.error(res.msg);
        }
      })
      .catch((err: any) => {
        message.error("系统异常");
      });
  };

  const deleteUserConfirm = (userId: number) => {
    Modal.confirm({
      title: "是否删除当前用户？",
      icon: <ExclamationCircleFilled />,
      okText: "是",
      cancelText: "否",
      onOk() {
        deleteUser(userId);
      },
    });
  };

  const deleteUser = (userId: number) => {
    let param = {
      userId: userId,
    };
    $get("/user/delete", param)
      .then((res: any) => {
        if (res.code === 0) {
          message.success(res.msg);
          setCurrentPage(1);
          search(1, 10);
        } else {
          message.error(res.msg);
        }
      })
      .catch((err: any) => {
        message.error("系统异常");
      });
  };

  const resetPassConfirm = (userId: number) => {
    Modal.confirm({
      title: "是否重置当前用户的密码？",
      icon: <ExclamationCircleFilled />,
      okText: "是",
      cancelText: "否",
      onOk() {
        resetPassword(userId);
      },
    });
  };

  const resetPassword = (userId: number) => {
    let param = {
      userId: userId,
    };
    $get("/user/resetPass", param)
      .then((res: any) => {
        if (res.code === 0) {
          message.success(res.msg);
        } else {
          message.error(res.msg);
        }
      })
      .catch((err: any) => {
        message.error("系统异常");
      });
  };

  const search = (pageNum: number, pageSize: number) => {
    let param = {
      pageNum: pageNum,
      pageSize: pageSize,
      ...searchForm.getFieldsValue(),
    };
    $get("/user/findByPage", param)
      .then((res: any) => {
        if (res.code === 0) {
          let userList = res.data.list.map((item: any) => {
            return {
              key: item.userId,
              ...item
            }
          })
          setUserList(userList);
          setTotal(res.data.total);
          setCurrentPage(pageNum);
        } else {
          message.error(res.msg);
        }
      })
      .catch((err: any) => {
        message.error("系统异常");
      });
  };

  const getRoleList = () => {
    $get("/role/findAll", null)
      .then((res: any) => {
        if (res.code === 0) {
          setRoleList(res.data);
        } else {
          message.error(res.msg);
        }
      })
      .catch((err: any) => {
        message.error("系统异常");
      });
  };

  const getDepartmentList = () => {
    $get("/department/find", searchForm.getFieldsValue())
      .then((res: any) => {
        if (res.code === 0) {
          let departmentList = TreeUtils.list2Tree(res.data, field);
          setDepartmentList(departmentList);
        } else {
          message.error(res.msg);
        }
      })
      .catch((err: any) => {
        message.error("系统异常");
      });
  }

  const resetDataForm = () => {
    dataForm.resetFields();
  };

  const resetSearchForm = () => {
    searchForm.resetFields();
  };

  const renderAvailable = () => {
    let options = availableList.map((option) => {
      return { label: option.availableName, value: option.available };
    });
    return <Select options={options} placeholder="用户状态" />;
  };

  const renderRoleSelect = () => {
    let options = roleList.map((option: any) => {
      return {
        label: option.roleName,
        value: option.roleId,
        disabled: option.available === 0,
      };
    });
    return <Select options={options} placeholder="角色" />;
  };

  return (
    <>
      <Modal
        title={infoModalTitle}
        open={infoModalShow}
        closable={true}
        onCancel={closeModal}
        footer={null}
      >
        <Form
          form={dataForm}
          labelAlign="right"
          layout="vertical"
          colon={false}
          onFinish={saveOrUpdate}
        >
          <Form.Item name="userId" hidden={true}>
            <Input />
          </Form.Item>
          <Form.Item
            name="nickName"
            label="用户名称"
            rules={[
              { required: true, type: "string", message: "请输入用户名称" },
              { max: 10, min: 2, message: "长度在2~10位之间" },
            ]}
          >
            <Input placeholder="用户名称" maxLength={10} />
          </Form.Item>
          <Form.Item
            name="username"
            label="用户账号"
            rules={[
              { required: true, type: "string", message: "请输入用户账号" },
              { max: 12, min: 5, message: "长度在5~12位之间" },
            ]}
          >
            <Input placeholder="用户账号" maxLength={12} />
          </Form.Item>
          <Form.Item
            name="mail"
            label="邮箱"
            rules={[{ max: 32, min: 8, message: "长度在8~32位之间" }]}
          >
            <Input placeholder="邮箱" maxLength={32} />
          </Form.Item>
          <Form.Item
            name="phone"
            label="手机号码"
            rules={[
              { required: true, type: "string", message: "请输入用户账号" },
              { max: 14, min: 7, message: "长度在7~14位之间" },
            ]}
          >
            <Input placeholder="手机号码" maxLength={14} />
          </Form.Item>
          <Form.Item
            name="deptId"
            label="所属部门"
            rules={[{ required: true, message: "请输入选择所属部门" }]}
          >
            <TreeSelect
              style={{ width: "100%" }}
              dropdownStyle={{ maxHeight: 400, overflow: "auto" }}
              placeholder="请选择所属部门"
              allowClear
              treeData={departmentList}
              fieldNames={{
                label: "deptName",
                value: "deptId",
                children: "children",
              }}
            />
          </Form.Item>
          <Form.Item
            name="roleId"
            label="角色"
            rules={[{ required: true, message: "请选择角色" }]}
          >
            {renderRoleSelect()}
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              保存
            </Button>
            <Button onClick={resetDataForm}>重置</Button>
          </Form.Item>
        </Form>
      </Modal>
      <div className="user-body">
        <div className="search-condition">
          <Form
            form={searchForm}
            labelAlign="left"
            name="horizontal_login"
            colon={false}
          >
            <div className="form-body">
              <Form.Item name="username" label="用户账号">
                <Input placeholder="用户账号" maxLength={12} />
              </Form.Item>
              <Form.Item name="nickName" label="用户名称">
                <Input placeholder="用户名称" maxLength={10} />
              </Form.Item>
              <Form.Item name="mail" label="邮箱">
                <Input placeholder="邮箱" maxLength={32} />
              </Form.Item>
              <Form.Item name="phone" label="手机号码">
                <Input placeholder="手机号码" maxLength={14} />
              </Form.Item>
              <Form.Item name="deptId" label="所属部门">
                <TreeSelect
                  style={{ width: "100%" }}
                  dropdownStyle={{ maxHeight: 400, overflow: "auto" }}
                  placeholder="请选择所属部门"
                  allowClear
                  treeData={departmentList}
                  fieldNames={{
                    label: "deptName",
                    value: "deptId",
                    children: "children",
                  }}
                />
              </Form.Item>
              <Form.Item name="available" label="状态">
                {renderAvailable()}
              </Form.Item>
            </div>
            <div className="form-footer">
              <Form.Item>
                <Button
                  type="primary"
                  icon={<SearchOutlined />}
                  onClick={() => search(1, 10)}
                >
                  查询
                </Button>
                <Button icon={<ReloadOutlined />} onClick={resetSearchForm}>
                  重置
                </Button>
              </Form.Item>
            </div>
          </Form>
        </div>
        <div className="table-area">
          <div className="operate-btn-group">
            <Button
              type="dashed"
              icon={<PlusOutlined />}
              onClick={() => switchDataModalShow(true, 0, null)}
              disabled={
                !permissionList || !permissionList.includes("system.user:save")
              }
            >
              新增
            </Button>
          </div>
          <div className="table-data">
            <Table
              dataSource={userList}
              columns={columns}
              scroll={{ x: 1200 }}
              pagination={{
                current: currentPage,
                total: total,
                onChange: search,
              }}
            />
          </div>
        </div>
      </div>
    </>
  );
};

export default App;
